﻿/****************************************************************************************************************
*                                                                                                               *
* Copyright (C) 2011 5173.com                                                                                   *
* This project may be copied only under the terms of the Apache License 2.0.                                    *
* Please visit the project Home Page http://bqqapicsharp.codeplex.com/ for more detail.                         *
*                                                                                                               *
****************************************************************************************************************/

namespace BQQAPIClient.Core.Network
{
    using System.Collections.Generic;
    using System.Net.Sockets;

    internal class BufferManager
    {
        private byte[] bufferBlock;
        private int currentIndex;
        private int totalBytes;
        private int bufferSize;
        private Stack<int> freeIndexPool;

        internal BufferManager(int totalBytes, int bufferSize)
        {
            this.totalBytes = totalBytes;
            this.bufferSize = bufferSize;
        }

        internal void Init()
        {
            this.currentIndex = 0;
            this.freeIndexPool = new Stack<int>();
            bufferBlock = new byte[totalBytes];
        }

        internal bool SetBuffer(SocketAsyncEventArgs args)
        {
            if (freeIndexPool.Count > 0)
            {
                args.SetBuffer(bufferBlock, freeIndexPool.Pop(), bufferSize);
            }
            else
            {
                if (totalBytes < (currentIndex + bufferSize))
                {
                    return false;
                }
                args.SetBuffer(bufferBlock, currentIndex, bufferSize);
                currentIndex += bufferSize;
            }
            return true;
        }

        internal void FreeBuffer(SocketAsyncEventArgs args)
        {
            freeIndexPool.Push(args.Offset);
            args.SetBuffer(null, 0, 0);
        }
    }
}
